import os
import configparser
import json
import sys


class GenerateServicesConfig:
    def __init__(self):
        self.config = configparser.RawConfigParser()
        self.types = ['mbtinfo', 'tpkinfo', 'c3dtinfo', 'slpkinfo']

    # 递归搜索指定文件夹内所有符合文件格式的配置文件
    def readServerConfigFiles(self, path):
        try:
            dirs = os.listdir(path)
            for i in dirs:
                if os.path.isfile(path + '/' + i):
                    # ns = ns + 1
                    try:
                        fileType = os.path.splitext(path + '/' + i)[1]
                        if fileType[1:] in self.types:
                            # self.readAndAddServer(path + '/' + i)
                            with open(path + '/' + i, encoding='utf-8') as f:
                                svr = json.load(f)

                                self.config.add_section(svr['serviceName'])
                                self.config.set(svr['serviceName'], 'config_path', path + '/' + i)

                    except Exception as e:
                        print(e)
                        print('初始化读取服务配置文件:' + path + '/' + i + '时出错')

                    # print('stop' + path + '/' + i)
                elif os.path.isdir(path + '/' + i):
                    # print('folder' + path + '/' + i)
                    self.readServerConfigFiles(path + '/' + i)

            # print(self.serviceList)
        except Exception as e:
            print(e)
            print('初始化读取服务配置文件:' + path + '时出错')

    def writeConfig(self, path):
        with open(path, 'w') as configfile:
            self.config.write(configfile)


if len(sys.argv) != 2:
    print('参数异常')
    sys.exit(1)

pa = sys.argv[1]
pa = pa.replace('//', '/')

gene = GenerateServicesConfig()
gene.readServerConfigFiles(pa)
gene.writeConfig(pa + '/services_list.conf')